package com.ktg.mes.wm.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chanjet.openapi.sdk.java.exception.ChanjetApiException;
import com.ktg.mes.chanjet.content.InventoryClassContent;
import com.ktg.mes.chanjet.response.InventoryClassResponse;
import com.ktg.mes.chanjet.spi.ChanjetSpi;
import com.ktg.mes.md.domain.MdItem;
import com.ktg.mes.wm.domain.WmWarehouse;
import org.springframework.data.repository.query.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.common.enums.BusinessType;
import com.ktg.mes.wm.domain.WmMaterialStock;
import com.ktg.mes.wm.service.IWmMaterialStockService;
import com.ktg.common.utils.poi.ExcelUtil;
import com.ktg.common.core.page.TableDataInfo;

/**
 * 库存记录Controller
 *
 * @author yinjinlu
 * @date 2022-05-30
 */
@RestController
@RequestMapping("/mes/wm/wmstock")
public class WmMaterialStockController extends BaseController {
    @Autowired
    private IWmMaterialStockService wmMaterialStockService;


    @Autowired
    private ChanjetSpi chanjetSpi;

    /**
     * 查询库存记录列表
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:wmstock:list')")
    @GetMapping("/list")
    public TableDataInfo list(WmMaterialStock wmMaterialStock) {
        startPage();
        List<WmMaterialStock> list = wmMaterialStockService.selectWmMaterialStockList(wmMaterialStock);
        return getDataTable(list);
    }

    /**
     * 导出库存记录列表
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:wmstock:export')")
    @Log(title = "库存记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmMaterialStock wmMaterialStock) {
        List<WmMaterialStock> list = wmMaterialStockService.selectWmMaterialStockList(wmMaterialStock);
        ExcelUtil<WmMaterialStock> util = new ExcelUtil<WmMaterialStock>(WmMaterialStock.class);
        util.exportExcel(response, list, "库存记录数据");
    }

    /**
     * 获取库存记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:wmstock:query')")
    @GetMapping(value = "/{materialStockId}")
    public AjaxResult getInfo(@PathVariable("materialStockId") Long materialStockId) {
        return AjaxResult.success(wmMaterialStockService.selectWmMaterialStockByMaterialStockId(materialStockId));
    }

//    /**
//     * 新增库存记录
//     */
//    @PreAuthorize("@ss.hasPermi('mes:wm:wmstock:add')")
//    @Log(title = "库存记录", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody WmMaterialStock wmMaterialStock)
//    {
//        return toAjax(wmMaterialStockService.insertWmMaterialStock(wmMaterialStock));
//    }
//
//    /**
//     * 修改库存记录
//     */
//    @PreAuthorize("@ss.hasPermi('mes:wm:wmstock:edit')")
//    @Log(title = "库存记录", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody WmMaterialStock wmMaterialStock)
//    {
//        return toAjax(wmMaterialStockService.updateWmMaterialStock(wmMaterialStock));
//    }


    /**
     * 同步T6信息
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:wmstock:syncStock')")
    @Log(title = "同步T6信息", businessType = BusinessType.UPDATE)
    @GetMapping("/syncStock")
    public AjaxResult syncStock() {
        wmMaterialStockService.sysnStock();
        return toAjax(1);
    }

//    /**
//     * 删除库存记录
//     */
//    @PreAuthorize("@ss.hasPermi('mes:wm:wmstock:remove')")
//    @Log(title = "库存记录", businessType = BusinessType.DELETE)
//	@DeleteMapping("/{materialStockIds}")
//    public AjaxResult remove(@PathVariable Long[] materialStockIds)
//    {
//        return toAjax(wmMaterialStockService.deleteWmMaterialStockByMaterialStockIds(materialStockIds));
//    }

    @GetMapping("/syncTpStock")
    @PreAuthorize("@ss.hasPermi('mes:wm:wmstock:sync')")
    public AjaxResult syncTpStock(@Param("id") Long id) throws ChanjetApiException {
        WmMaterialStock wmMaterialStock = wmMaterialStockService.getById(id);
        InventoryClassContent content = new InventoryClassContent();
        JSONObject isBatch = new JSONObject();
        isBatch.putOpt("IsBatch",true);
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOpt("Code",wmMaterialStock.getItemCode());
        JSONObject warehouse = new JSONObject();
        warehouse.putOpt("Code",wmMaterialStock.getWarehouseCode());
        List wareList = new ArrayList();
        wareList.add(warehouse);
        List list = new ArrayList();
        list.add(jsonObject);
        JSONObject inventory = new JSONObject();
        inventory.putOpt("Inventory",list);
        inventory.putOpt("Warehouse",wareList);
        inventory.putOpt("GroupInfo",isBatch);
        content.setParam(inventory);
        InventoryClassResponse response = chanjetSpi.getStockList(content);
        List<Map> data = response.getData();
        List<Map> filterList = data.stream().filter(dataMap -> {
            if (wmMaterialStock.getWarehouseCode().equals(dataMap.get("WarehouseCode")) &&
                    wmMaterialStock.getBatchCode().equals(dataMap.get("Batch")) &&
                    wmMaterialStock.getItemCode().equals(dataMap.get("InventoryCode"))
            ) return true;
            return false;
        }).collect(Collectors.toList());
        if(filterList.size() == 0) return AjaxResult.error("商品查无库存相关信息");
        Map map = filterList.get(0);
        if(!(map.get("InventoryCode").equals(wmMaterialStock.getItemCode()))) return AjaxResult.error("更新内容不匹配");
        WmMaterialStock stock = new WmMaterialStock();
        stock.setMaterialStockId(wmMaterialStock.getMaterialStockId());
        stock.setItemId(new BigDecimal((String)map.get("InventoryID")).longValue());
        stock.setItemName((String)map.get("InventoryName"));
        stock.setItemCode((String)map.get("InventoryCode"));
        stock.setItemType((String)map.get("InventoryClassName"));
        stock.setQuantityOnhand(new BigDecimal((String) map.get("AvailableQuantity")));
        stock.setExistingQuantity(new BigDecimal((String) map.get("ExistingQuantity")));
        if(map.get("WarehouseID") !=null && !map.get("WarehouseID").equals("")){
            stock.setWarehouseId(new BigDecimal((String)map.get("WarehouseID")).longValue());
            stock.setWarehouseCode((String)map.get("WarehouseCode"));
            stock.setWarehouseName((String)map.get("WarehouseName"));
        }
        stock.setBatchCode((String)map.get("Batch"));
        stock.setLocationName((String)map.get("InvLocationName"));
        stock.setLocationCode((String)map.get("InvLocationCode"));
        stock.setUnitOfMeasure((String)map.get("UnitName"));
        stock.setUpdateTime(new Date());
        wmMaterialStockService.saveOrUpdate(stock);
        return AjaxResult.success("更新成功");
    }
}
